/*******************************************************************************
 * Copyright 2011 Alexandre Zglav and Morphiastic
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.morphiastic.analysis.tokenizers;

import java.io.IOException;
import java.util.Map;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;

import com.morphiastic.analysis.AnalysisComponentDefinition;
import com.morphiastic.utils.EqualsUtil;


public class KeywordTokenizer extends ElasticTokenizer{

	public static final String BUFFER_SIZE_PARAM_KEY = "buffer_size";
	
	private Integer bufferSize;
	
	
	
	public KeywordTokenizer(String defName) {
		this(null, defName);
	}

	public KeywordTokenizer(Map<String,String> params, String defName) {
		super(ElasticTokenizerType.keyword, defName);
		
		if(params!=null){
			String bstr = params.get(BUFFER_SIZE_PARAM_KEY);
			if(bstr!=null && !bstr.isEmpty()){
				try {
					int b = Integer.parseInt(bstr);
					this.bufferSize = b;
				} catch (NumberFormatException e) {
				}
			}
		}
	}
	
	
	
	
	
	

	@Override
	public boolean hasCustomParams() {
		 if(this.bufferSize!= null && this.bufferSize!=256)return true;
		 return false;
	}
	
	
	@Override
	public XContentBuilder addToBuilder(
			XContentBuilder mappingBuilder) throws IOException {
		mappingBuilder.startObject(getDefName())
		.field("type", getElasticTokenizerType().toString());
		
		if(this.bufferSize != null){
			mappingBuilder.field(BUFFER_SIZE_PARAM_KEY, this.bufferSize);
		}
		return mappingBuilder;
	}

	
	
	@Override
	public void setParamsFromSettings(Settings tokenizerSettings) {
		String bsizeSet = tokenizerSettings.get(BUFFER_SIZE_PARAM_KEY);
		if(bsizeSet!=null && !bsizeSet.isEmpty()){
			try {
				int mtl = Integer.parseInt(bsizeSet);
				this.bufferSize = mtl;
			} catch (NumberFormatException e) {
			}
		}
	}
	
	@Override
	public boolean areEquivalentDefinitions(AnalysisComponentDefinition otherTok){
		
		if(otherTok==null)return false;
		KeywordTokenizer ot ;
		try {
			ot = (KeywordTokenizer)otherTok;
		} catch (ClassCastException e) {
			return false;
		}
		return 
		EqualsUtil.areEqual(this.bufferSize, ot.bufferSize);
	}
	
}
